package com.xxwy.searchtree;


import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @author xxwy
 */
public class BST<E extends Comparable<E>> {


    private class Node {
        public E e;
        public Node left, right;

        public Node(E e) {
            this.e = e;
            right = null;
            left = null;
        }
    }

    private Node root;
    private int size;

    public BST() {
        root = null;
        size = 0;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void add(E e) {
        root = add(root, e);
    }

    //返回插入新节点的二分搜索树的根
    private Node add(Node node, E e) {
        if (node == null) {
            size++;
            return new Node(e);
        }
        if (e.compareTo(node.e) < 0) {
            node.left = add(node.left, e);
        } else if (e.compareTo(node.e) > 0) {
            node.right = add(node.right, e);
        }
        return node;
    }

    /**
     * 删除最小
     *
     * @param e
     */
    public void remove(E e) {
        if (isEmpty()) {
            throw new IllegalArgumentException("BST is empty");
        }
        Node node = remove(root, e);
    }

    /**
     * 返回的是删除之后，这个节点的新节点
     *
     * @param node
     * @param e
     * @return
     */
    private Node remove(Node node, E e) {
        if (node == null) {
            return null;
        }
        if (node.e.compareTo(e) < 0) {
            node.left = remove(node.left, e);
            return node;
        } else if (node.e.compareTo(e) > 0) {
            node.right = remove(node.right, e);
            return node;
        } else {
            //左子树为null
            if (node.left == null) {
                Node rightNode = node.right;
                size--;
                node.right = null;
                return rightNode;
            }
            //右子树为null
            if (node.right == null) {
                Node leftNode = node.left;
                size--;
                node.left = null;
                return leftNode;
            }
            if (node.right != null) {
                minmum(node.right);
            }
            //左右节点都不为null,找到比待删除节点大中的最小节点，待删除节点右子树的最小节点
            //用这个节点顶替删除节点的位置
            Node successor = minmum(node.right);
            successor.right = removeMin(node.right);
            successor.left = node.left;
            node.left = node.right = null;
            //在removeMin中做个size--，so不用再次删除
            return successor;
        }
    }


    /**
     * 找到最小值
     *
     * @return
     */
    public E minmum() {
        if (isEmpty()) {
            throw new IllegalArgumentException("BST is empty");
        }
        return minmum(root).e;
    }

    private Node minmum(Node node) {
        if (node.left == null) {
            return node;
        }
        return minmum(node.left);
    }

    /**
     * 找到最大值
     *
     * @return
     */
    public E maxmum() {
        if (isEmpty()) {
            throw new IllegalArgumentException("BST is empty");
        }
        return maxmum(root).e;
    }

    private Node maxmum(Node node) {
        if (node.right == null) {
            return node;
        }
        return minmum(node.right);
    }

    public E removeMin() {
        //最右边
        if (isEmpty()) {
            throw new IllegalArgumentException("BST is empty");
        }
        E minmum = minmum();
        removeMin(root);
        return minmum;
    }

    /**
     * 删除node节点的最小节点
     * 返回删除节点后新的二分搜索树的根
     *
     * @param node
     * @return
     */
    private Node removeMin(Node node) {
        if (node.left == null) {
            Node rightNode = node.right;
            node.right = null;
            size--;
            return rightNode;
        }
        node.left = removeMin(node.left);
        return node;

    }

    /**
     * 删除最大值
     */
    public E removeMax() {
        //最右边
        if (isEmpty()) {
            throw new IllegalArgumentException("BST is empty");
        }
        E maxmum = maxmum();
        removeMax(root);
        return maxmum;

    }

    /**
     * 删除node节点的最大节点
     * 返回删除节点后新的二分搜索树的根
     *
     * @param node
     * @return
     */
    private Node removeMax(Node node) {
        if (node.right == null) {
            Node leftNode = node.left;
            node.left = null;
            size--;
            return leftNode;

        }
        node.right = removeMax(node.right);
        return node;
    }


    /**
     * 删除最小值
     */
    public E removeMinNR() {
        //最左边
        if (isEmpty()) {
            throw new IllegalArgumentException("BST is empty");
        }
        Node cur = root;
        Node pre = null;
        while (cur.left != null) {
            pre = cur;
            cur = cur.left;
        }
        if (pre == null) {
            //删除的是当前值root值，
            root = null;
        } else if (cur.right == null) {
            pre.left = null;
        } else {//cur.right != null
            pre.left = cur.right;
        }
        size--;
        return cur.e;
    }

    public boolean contains(E e) {
        if (e == null) {
            return false;
        }
        return contains(root, e);
    }

    private boolean contains(Node node, E e) {
        //处理终止操作
        if (node == null) {
            return false;
        }
        if (node.e.equals(e)) {
            return true;
        } else if (node.e.compareTo(e) < 0) {
            return contains(node.left, e);
        } else {//node.e.compareTo(e)>0
            return contains(node.right, e);
        }
    }

    /**
     * 遍历操作,前序
     */
    public void preOrder() {
        preOrder(root);
    }

    private void preOrder(Node node) {
        if (node == null) {
            return;
        }
        doPrint(node.e);
        preOrder(node.left);
        preOrder(node.right);
    }

    /**
     * 遍历操作，中序
     */
    public void inOrder() {
        inOrder(root);
    }

    private void inOrder(Node node) {
        if (node == null) {
            return;
        }
        inOrder(node.left);
        doPrint(node.e);
        inOrder(node.right);
    }

    /**
     * 遍历操作，后序
     */
    public void postOrder() {
        postOrder(root);
    }

    private void postOrder(Node node) {
        if (node == null) {
            return;
        }
        doPrint(node.e);
        postOrder(node.left);
        postOrder(node.right);
    }

    //遍历操作，前序非递归，使用栈
    private void preOrderNR() {
        if (root != null) {
            Stack<Node> stack = new Stack<>();
            stack.push(root);
            //栈不为空
            while (stack != null) {
                //弹出的时候压入右再左
                Node cur = stack.pop();
                doPrint(cur.e);
                //栈是先进后出，所以先压入右子树
                if (cur.right != null) {
                    stack.push(cur.right);
                }
                if (cur.left != null) {
                    stack.push(cur.left);
                }
            }
        }
    }

    /**
     * 层序遍历
     */
    public void levelOrder() {
        Queue<Node> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            Node cur = queue.remove();
            doPrint(cur.e);
            if (cur.left != null) {
                queue.add(cur.left);
            }
            if (cur.right != null) {
                queue.add(cur.right);
            }
        }
    }

    private void doPrint(E e) {
        System.out.println(e);
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        generateBSTString(root, 0, res);
        return res.toString();
    }

    /**
     * 生成以node为根节点，深度为depth的描述二叉树的字符串
     *
     * @param node
     * @param depth
     * @param res
     */
    private void generateBSTString(Node node, int depth, StringBuilder res) {
        if (node == null) {
            res.append(generateDepthString(depth) + "null\n");
            return;
        }
        res.append(generateDepthString(depth) + node.e + "\n");
        generateBSTString(node.left, depth + 1, res);
        generateBSTString(node.right, depth + 1, res);

    }

    private String generateDepthString(int depth) {
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            res.append("--");
        }
        return res.toString();
    }

}

